package com.industrial.premu.service.impl.sqsj;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.DgQuantityQualityManage;
import com.industrial.premu.domain.SysOperError;
import com.industrial.premu.domain.sqsj.PreMuImportGuotu;
import com.industrial.premu.domain.sqsj.PreMuImportHuanbao;
import com.industrial.premu.domain.sqsj.PreMuImportLog;
import com.industrial.premu.mapper.DgQuantityQualityManageMapper;
import com.industrial.premu.mapper.SysOperErrorMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportGuotuMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportLogMapper;
import com.industrial.premu.service.IPreMuImportGuotuService;
import com.industrial.premu.service.IPreMuImportLogService;
import com.industrial.premu.util.ValidationUtil;
import com.industrial.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


/**
 * 亩产导入数据-自然资源和规划局Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-25
 */
@Service
public class PreMuImportGuotuServiceImpl implements IPreMuImportGuotuService
{
    @Autowired
    private PreMuImportGuotuMapper preMuImportGuotuMapper;

    private static final int BATCH_SIZE = 300;

    @Autowired
    private SysOperErrorMapper sysOperErrorMapper;

    @Autowired
    private DgQuantityQualityManageMapper dgQuantityQualityManageMapper;

    private static final Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)?$");

    /**
     * 查询亩产导入数据-自然资源和规划局
     *
     * @param id 亩产导入数据-自然资源和规划局主键
     * @return 亩产导入数据-自然资源和规划局
     */
    @Override
    public PreMuImportGuotu selectPreMuImportGuotuById(String id)
    {
        return preMuImportGuotuMapper.selectPreMuImportGuotuById(id);
    }

    /**
     * 查询亩产导入数据-自然资源和规划局列表
     *
     * @param preMuImportGuotu 亩产导入数据-自然资源和规划局
     * @return 亩产导入数据-自然资源和规划局
     */
    @Override
    public List<PreMuImportGuotu> selectPreMuImportGuotuList(PreMuImportGuotu preMuImportGuotu)
    {
        return preMuImportGuotuMapper.selectPreMuImportGuotuList(preMuImportGuotu);
    }

    /**
     * 新增亩产导入数据-自然资源和规划局
     *
     * @param preMuImportGuotu 亩产导入数据-自然资源和规划局
     * @return 结果
     */
    @Override
    public int insertPreMuImportGuotu(PreMuImportGuotu preMuImportGuotu)
    {
        return preMuImportGuotuMapper.insertPreMuImportGuotu(preMuImportGuotu);
    }

    /**
     * 修改亩产导入数据-自然资源和规划局
     *
     * @param preMuImportGuotu 亩产导入数据-自然资源和规划局
     * @return 结果
     */
    @Override
    public int updatePreMuImportGuotu(PreMuImportGuotu preMuImportGuotu)
    {
        return preMuImportGuotuMapper.updatePreMuImportGuotu(preMuImportGuotu);
    }

    /**
     * 批量删除亩产导入数据-自然资源和规划局
     *
     * @param ids 需要删除的亩产导入数据-自然资源和规划局主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportGuotuByIds(String[] ids)
    {
        return preMuImportGuotuMapper.deletePreMuImportGuotuByIds(ids);
    }

    /**
     * 删除亩产导入数据-自然资源和规划局信息
     *
     * @param id 亩产导入数据-自然资源和规划局主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportGuotuById(String id)
    {
        return preMuImportGuotuMapper.deletePreMuImportGuotuById(id);
    }

    @Autowired
    private PreMuImportLogMapper preMuImportLogMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeData(PreMuImportGuotu params,String deptCode) {
        preMuImportGuotuMapper.removeData(params);

        PreMuImportLog removeParams = new PreMuImportLog();
        removeParams.setYear(params.getYear());
        removeParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        removeParams.setDeptCode(deptCode);
        preMuImportLogMapper.removeData(removeParams);
    }

    @Override
    public AjaxResult importGuotuExcelData(String year, String companyType, MultipartFile file) {
        try{
            ExcelUtil<PreMuImportGuotu> util = new ExcelUtil<PreMuImportGuotu>(PreMuImportGuotu.class);
            List<PreMuImportGuotu> preMuImportTongjis = util.importExcel(file.getInputStream());
            if (StringUtils.isNull(preMuImportTongjis) || preMuImportTongjis.size() == 0) {
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("allMsg","导入数据不能为空");
                return AjaxResult.error("导入失败",resultMap);
            }
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            int successNum = 0;
            int failureNum = 0;
            int updateNum = 0;

            //企业名称为空的错误数据量
            int companyNameBlankCount = 0;
            //值为空的错误量
            int valueZeroCount = 0;
            int valueErrorCount = 0;

            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();
            StringBuilder allMsg = new StringBuilder();

            List<String> usccList = new ArrayList<String>();
            List<PreMuImportGuotu> realList = new ArrayList<PreMuImportGuotu>();
            List<String> mcImportExistList = new ArrayList<String>();

            List<PreMuImportGuotu> addImportList = new ArrayList<PreMuImportGuotu>();
            List<PreMuImportGuotu> updateImportList = new ArrayList<PreMuImportGuotu>();

            if (preMuImportTongjis != null && !preMuImportTongjis.isEmpty()) {

                preMuImportTongjis.forEach(data -> {
                    if (data.getUscc() != null && !"".equals(data.getUscc())){
                        usccList.add(data.getUscc().trim());
                        realList.add(data);
                    }
                });
            }

            long count = usccList.stream().distinct().count();
            boolean isRepeat = count < usccList.size();
            if (isRepeat) {
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("allMsg","有重复统一社会信用代码，请检查导入数据！");
                return AjaxResult.error("导入失败",resultMap);
            }

            if(!usccList.isEmpty()){
                mcImportExistList = preMuImportGuotuMapper.getImportGuotuExistList(year, usccList);
            }
            ValidationUtil.validate(realList);
            //行数
            int travel = 1;
            for (int i = 0; i < preMuImportTongjis.size(); i++) {
                travel++;
                PreMuImportGuotu mcImportGuotuDO = preMuImportTongjis.get(i);

                if(mcImportGuotuDO.getSumArea() == null || !pattern.matcher(mcImportGuotuDO.getSumArea()+"").matches() || mcImportGuotuDO.getSumArea().doubleValue() ==0){
                    BigDecimal userArea = new BigDecimal(0);
                    BigDecimal otherArea = new BigDecimal(0);
                    BigDecimal leasedArea = new BigDecimal(0);
                    BigDecimal rentOutArea = new BigDecimal(0);
                    BigDecimal sumArea = new BigDecimal(0);

                    if(mcImportGuotuDO.getUseArea() != null && pattern.matcher(mcImportGuotuDO.getUseArea()+"").matches()){
                        userArea = new BigDecimal(mcImportGuotuDO.getUseArea()+"");
                    }
                    if(mcImportGuotuDO.getOtherArea() != null && pattern.matcher(mcImportGuotuDO.getOtherArea()+"").matches()){
                        otherArea = new BigDecimal(mcImportGuotuDO.getOtherArea()+"");
                    }
                    if(mcImportGuotuDO.getLeasedArea() != null && pattern.matcher(mcImportGuotuDO.getLeasedArea()+"").matches()){
                        leasedArea = new BigDecimal(mcImportGuotuDO.getLeasedArea()+"");
                    }
                    if(mcImportGuotuDO.getRentOutArea() != null && pattern.matcher(mcImportGuotuDO.getRentOutArea()+"").matches()){
                        rentOutArea = new BigDecimal(mcImportGuotuDO.getRentOutArea()+"");
                    }
                    sumArea = userArea.add(otherArea).add(leasedArea).subtract(rentOutArea);
                    mcImportGuotuDO.setSumArea(sumArea);
                }

                mcImportGuotuDO.setYear(year);
                String uscc = mcImportGuotuDO.getUscc();
                if (uscc == null || "".equals(uscc) || year == null || "".equals(year)) {
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、企业 " + mcImportGuotuDO.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "企业社会信用代码或年份不能为空");
                    continue;
                }else{
                    uscc = uscc.trim();
                    mcImportGuotuDO.setUscc(uscc);
                }

                if(StringUtils.isBlank(mcImportGuotuDO.getCompanyName())){
                    companyNameBlankCount++;
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、企业 " + mcImportGuotuDO.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "企业名称不能为空");
                    continue;
                }

                if(mcImportGuotuDO.getSumArea() == null){
                    valueErrorCount++;
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、企业 " + mcImportGuotuDO.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "用地面积不能为空");
                    continue;
                }

                if(mcImportGuotuDO.getSumArea().compareTo(BigDecimal.ZERO) < 1){
                    valueZeroCount++;
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、企业 " + mcImportGuotuDO.getCompanyName() + " 导入失败：";
                    failureMsg.append(msg + "用地面积值不能小于或等于0");
                    continue;
                }

                if (mcImportExistList.contains(uscc)) {
                    mcImportGuotuDO.setDelFlag("0");
                    mcImportGuotuDO.setCompanyType(companyType);
                    updateImportList.add(mcImportGuotuDO);
                } else {
                    mcImportGuotuDO.setId(UUID.randomUUID().toString().replace("-", ""));
                    mcImportGuotuDO.setDelFlag("0");
                    mcImportGuotuDO.setCompanyType(companyType);
                    addImportList.add(mcImportGuotuDO);
                }

                if (addImportList != null && addImportList.size() >= BATCH_SIZE) {
                    int importNum = preMuImportGuotuMapper.batchSave(addImportList);
                    successNum += importNum;
                    addImportList.clear();

                }
                if (updateImportList != null && updateImportList.size() >= BATCH_SIZE) {
                    int importNum = preMuImportGuotuMapper.batchUpdateByUscc(year, updateImportList);
                    successNum += importNum;
                    updateNum += importNum;
                    updateImportList.clear();

                }
            }

            if (addImportList != null && !addImportList.isEmpty()) {
                int importNum = preMuImportGuotuMapper.batchSave(addImportList);
                successNum += importNum;
                addImportList.clear();

            }
            if (updateImportList != null && !updateImportList.isEmpty()) {
                int importNum = preMuImportGuotuMapper.batchUpdateByUscc(year, updateImportList);
                successNum += importNum;
                updateNum += importNum;
                updateImportList.clear();
            }

            if (failureNum > 0) {
                allMsg.insert(0, "<br/>很抱歉，错误如下：" + failureMsg.toString());
            }
            if (successNum > 0) {
                allMsg.insert(0, "恭喜您，共" + successNum + " 条数据导入成功！");
            }

            //企业名称为空的数量
            if(companyNameBlankCount > 0){
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("自然资源和规划局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("企业名称不能为空");
                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(companyNameBlankCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }else{
                    comapnNameBlankParams.setBaseId(IdUtil.simpleUUID());
                    comapnNameBlankParams.setBaseCreateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseCreateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setBaseUpdateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseUpdateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setFailCount(String.valueOf(companyNameBlankCount));
                    comapnNameBlankParams.setRuleType("1");
                    dgQuantityQualityManageMapper.insertDgQuantityQualityManage(comapnNameBlankParams);
                }
            }else{
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("自然资源和规划局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("企业名称不能为空");
                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(companyNameBlankCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }
            }
            //值小于0错误的情况
            if(valueZeroCount > 0){
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("自然资源和规划局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("值小于0的错误");

                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(valueZeroCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }else{
                    comapnNameBlankParams.setBaseId(IdUtil.simpleUUID());
                    comapnNameBlankParams.setBaseCreateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseCreateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setBaseUpdateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseUpdateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setFailCount(String.valueOf(valueZeroCount));
                    comapnNameBlankParams.setRuleType("1");
                    dgQuantityQualityManageMapper.insertDgQuantityQualityManage(comapnNameBlankParams);
                }
            }else{
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("自然资源和规划局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("值小于0的错误");
                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(valueZeroCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }
            }

            //值不存在错误的情况
            if(valueErrorCount > 0){
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("自然资源和规划局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("值不存在或者是格式有误");

                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(valueErrorCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }else{
                    comapnNameBlankParams.setBaseId(IdUtil.simpleUUID());
                    comapnNameBlankParams.setBaseCreateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseCreateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setBaseUpdateTime(DateUtils.getNowDate());
                    comapnNameBlankParams.setBaseUpdateBy(SecurityUtils.getUserId());
                    comapnNameBlankParams.setFailCount(String.valueOf(valueErrorCount));
                    comapnNameBlankParams.setRuleType("1");
                    dgQuantityQualityManageMapper.insertDgQuantityQualityManage(comapnNameBlankParams);
                }
            }else{
                DgQuantityQualityManage comapnNameBlankParams = new DgQuantityQualityManage();
                comapnNameBlankParams.setSource("自然资源和规划局");
                comapnNameBlankParams.setYears(year);
                comapnNameBlankParams.setProvince(sysUser.getProvince());
                comapnNameBlankParams.setCity(sysUser.getCity());
                comapnNameBlankParams.setCounty(sysUser.getDistrict());
                comapnNameBlankParams.setRuleName("值不存在或者是格式有误");
                List<DgQuantityQualityManage> dgQuantityQualityManages = dgQuantityQualityManageMapper.selectDgQuantityQualityManageList(comapnNameBlankParams);
                if(dgQuantityQualityManages != null && !dgQuantityQualityManages.isEmpty()){
                    DgQuantityQualityManage dgQuantityQualityManage = dgQuantityQualityManages.get(0);
                    dgQuantityQualityManage.setBaseUpdateTime(DateUtils.getNowDate());
                    dgQuantityQualityManage.setBaseUpdateBy(SecurityUtils.getUserId());
                    dgQuantityQualityManage.setFailCount(String.valueOf(valueErrorCount));
                    dgQuantityQualityManageMapper.updateDgQuantityQualityManage(dgQuantityQualityManage);
                }
            }

            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("msg","恭喜您，共" + successNum + " 条数据导入成功！");
            resultMap.put("sum",String.valueOf(successNum));
            resultMap.put("updateNum",String.valueOf(updateNum));
            resultMap.put("failureNum",String.valueOf(failureNum));
            resultMap.put("allMsg",allMsg.toString());
            return AjaxResult.success(resultMap);
        }catch (Exception e){
            String requestURI = "/industrial-premu/importExcelData";
            SysOperError sysOperError = new SysOperError();
            sysOperError.setBaseId(IdUtil.simpleUUID());
            sysOperError.setBaseCreateTime(new Date());
            sysOperError.setErrorMsg(e.getMessage());
            sysOperError.setUrlAddress(requestURI);
            sysOperError.setOperId(SecurityUtils.getUserId());
            sysOperErrorMapper.saveErrorInfo(sysOperError);
            e.printStackTrace();
            return AjaxResult.warn("导入失败");
        }
    }
}